package jd.se.homecontent;

import jd.se.common.Result;
import jd.se.common.Utils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

@WebServlet({
        "/homecontent/bookList",
        "/bookcover"
})
public class HomeBookAPI extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        String path = request.getServletPath();
        if("/homecontent/bookList".equals(path)){
            request.setCharacterEncoding("UTF-8");
            QueryDto queryDto = new QueryDto();

            try {
                queryDto.setPageNum(Integer.parseInt(request.getParameter("pageNum")));
            } catch (Exception e) {}

            try {
                queryDto.setPageSize(Integer.parseInt(request.getParameter("pageSize")));
            } catch (Exception e) {}


            //创建业务模型对象（服务对象/Service对象），通过业务对象执行业务方法
            HomeBookService homeBookService = new HomeBookService();
            Map<String,Object> page =  homeBookService.getBookList(queryDto);

            Utils.outResult(resp, Result.success(page));
        }
        if ("/bookcover".equals(path)){
            //从请求参数中通过参数名称filename获取文件名称
            String filename = request.getParameter("filename");
            //读取文件的输入流
            InputStream in = new FileInputStream("D:/git/bookcover"+"/"+filename);
            //将文件信息输出到浏览器的输出流
            OutputStream out = resp.getOutputStream();
            byte[] b = new byte[10240];//容量为10240字节的缓存区
            int len = -1;//从输入流读取并放入缓存区的数据量
            while((len=in.read(b)) != -1){
                out.write(b,0,len);
            }
            out.flush();
            out.close();
            in.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
